<template>
    <div class="org">
        <div class="contact">
            <div class="search">
                <el-input placeholder="搜索" prefix-icon="el-icon-search" v-model="search" size="small" clearable>
                </el-input>
            </div>
            <div>
                <el-tree
                    :data="treeData"
                    :default-expanded-keys="['100']"
                    node-key="code"
                    @node-click="handleNodeClick"
                    :props="props"
                    :filter-node-method="filterNode"
                    ref="tree"
                    highlight-current
                    @node-contextmenu="handleContextMenu"
                    :expand-on-click-node="false"
                    style="height:595px;overflow:auto;"
                >
                    <span slot-scope="{ node, data }" style="font-size: 13px">
                        <span style="margin-right: 5px">{{ data.code }}</span>
                        <span>{{ node.label }}</span>
                    </span>
                </el-tree>
            </div>
        </div>
        <div style="width: 637px; box-sizing: border-box">
            <div
                style="
                    height: 56px;
                    line-height: 56px;
                    padding-left: 15px;
                    border-bottom: 1px solid #eee;
                    font-weight: bold;
                "
                v-if="type == 2"
            >
                <el-button plain size="small" icon="el-icon-plus" @click="handleCommand('addUser')">添加</el-button>
                <el-button plain size="small" icon="el-icon-edit" @click="handleCommand('editUser')">编辑</el-button>
                <el-button plain size="small" icon="el-icon-delete" @click="handleCommand('deleteUser')"
                    >删除</el-button
                >
                <el-button plain size="small" icon="el-icon-unlock" @click="handleCommand('resetPassword')"
                    >重置密码</el-button
                >
                <el-dropdown @command="handleMore">
                    <el-button size="small" style="margin-left: 10px">
                        更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item icon="el-icon-download" command="template">下载模板</el-dropdown-item>
                        <el-upload
                            :action="action"
                            :show-file-list="false"
                            :headers="headers"
                            :before-upload="beforeUpload"
                            :on-success="successHandle"
                        >
                            <el-dropdown-item icon="el-icon-upload2">用户导入</el-dropdown-item>
                        </el-upload>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <div>
                <el-table
                    ref="multipleTable"
                    :data="tableData"
                    stripe
                    border
                    style="width: 100%; margin-top: 5px; border-bottom-right-radius: 12px"
                    :height="type == 1 ? 654 : 597"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column type="selection" width="50" align="center"> </el-table-column>
                    <el-table-column prop="name" label="姓名" align="center" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="sex" label="性别" align="center" width="60" :formatter="sexFormatter">
                    </el-table-column>
                    <el-table-column prop="phone" label="手机号" align="center" header-align="center" width="100">
                    </el-table-column>
                    <el-table-column prop="position" label="岗位" align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="email" label="邮箱" align="center" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="status" label="状态" align="center">
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.status"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="2"
                                @change="statusChange(scope.row, $event)"
                            >
                            </el-switch>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column
                        prop="status"
                        label="状态"
                        align="center"
                        header-align="center"
                        width="60"
                        :formatter="statusFormatter"
                    >
                    </el-table-column> -->
                </el-table>
            </div>
        </div>
        <!--新增部门-->
        <el-dialog
            title="新增"
            width="500px"
            :visible.sync="addFormVisible"
            :close-on-click-modal="false"
            append-to-body
        >
            <el-form :model="addForm" label-width="60px" :rules="formRules" ref="addForm">
                <el-form-item label="编码" prop="code">
                    <el-input v-model.trim="addForm.code" placeholder="请输入编码" maxlength="3" show-word-limit>
                        <template slot="prepend">{{ selected.code }}</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model.trim="addForm.name" placeholder="请输入名称"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addSubmit">提交</el-button>
            </div>
        </el-dialog>
        <!--编辑部门-->
        <el-dialog
            title="编辑"
            width="500px"
            :visible.sync="editFormVisible"
            :close-on-click-modal="false"
            append-to-body
        >
            <el-form :model="editForm" label-width="60px" :rules="formRules" ref="editForm">
                <!-- <el-form-item label="编码" prop="code">
                    <el-input v-model.trim="editForm.code" placeholder="请输入编码" maxlength="3" show-word-limit>
                    </el-input>
                </el-form-item> -->
                <el-form-item label="名称" prop="name">
                    <el-input v-model.trim="editForm.name" placeholder="请输入名称"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click="editSubmit">提交</el-button>
            </div>
        </el-dialog>
        <!--新增用户-->
        <el-dialog
            title="新增"
            width="750px"
            :visible.sync="addUserFormVisible"
            :close-on-click-modal="false"
            append-to-body
        >
            <el-form :model="addUserForm" label-width="80px" :rules="userRules" ref="addUserForm">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="所属部门" prop="departId">
                            <el-cascader
                                v-model="addUserForm.departId"
                                :options="treeData"
                                :props="{ checkStrictly: true, emitPath: false, label: 'name', value: 'id' }"
                                clearable
                                filterable
                                placeholder="请选择所属部门"
                            >
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model.trim="addUserForm.name" placeholder="请输入姓名"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="addUserForm.sex" placeholder="请选择性别">
                                <el-option label="男" :value="1"> </el-option>
                                <el-option label="女" :value="2"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="岗位" prop="position">
                            <el-input v-model.trim="addUserForm.position" placeholder="请输入岗位"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model.trim="addUserForm.phone" placeholder="请输入手机号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model.trim="addUserForm.email" placeholder="请输入邮箱"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="排序号" prop="sort">
                            <el-input-number v-model="addUserForm.sort" :min="1" label="请输入排序号"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addUserFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addUserSubmit">提交</el-button>
            </div>
        </el-dialog>
        <!--编辑用户-->
        <el-dialog
            title="编辑"
            width="750px"
            :visible.sync="editUserFormVisible"
            :close-on-click-modal="false"
            append-to-body
        >
            <el-form :model="editUserForm" label-width="80px" :rules="userRules" ref="editUserForm">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="所属部门" prop="departId">
                            <el-cascader
                                v-model="editUserForm.departId"
                                :options="treeData"
                                :props="{ checkStrictly: true, emitPath: false, label: 'name', value: 'id' }"
                                clearable
                                filterable
                                placeholder="请选择所属部门"
                            >
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model.trim="editUserForm.name" placeholder="请输入姓名"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="editUserForm.sex" placeholder="请选择性别">
                                <el-option label="男" :value="1"> </el-option>
                                <el-option label="女" :value="2"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="岗位" prop="position">
                            <el-input v-model.trim="editUserForm.position" placeholder="请输入岗位"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model.trim="editUserForm.phone" placeholder="请输入手机号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model.trim="editUserForm.email" placeholder="请输入邮箱"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="排序号" prop="sort">
                            <el-input-number
                                v-model="editUserForm.sort"
                                :min="1"
                                label="请输入排序号"
                            ></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-switch v-model="editUserForm.status" :active-value="1" :inactive-value="2"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editUserFormVisible = false">取消</el-button>
                <el-button type="primary" @click="editUserSubmit">提交</el-button>
            </div>
        </el-dialog>
        <div id="contextMenu" class="contextMenu">
            <div><i class="el-icon-plus" @click="handleCommand('addDepart')"> 新增</i></div>
            <div><i class="el-icon-edit" @click="handleCommand('editDepart')"> 编辑</i></div>
            <div><i class="el-icon-delete" @click="handleCommand('deleteDepart')"> 删除</i></div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            action: this.$axios.defaults.baseURL + 'user/import',
            headers: {
                Authorization: localStorage.getItem('Authorization')
            },
            search: '',
            props: {
                label: 'name'
            },
            treeData: [],
            tableData: [],
            selected: {},
            multipleSelection: [],
            addFormVisible: false,
            addForm: {
                code: '',
                name: ''
            },
            formRules: {
                code: [
                    { required: true, message: '请输入编码', trigger: 'blur' },
                    { min: 3, max: 3, message: '长度在 3个字符', trigger: 'blur' }
                ],
                name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
            },
            editFormVisible: false,
            editForm: {
                code: '',
                name: ''
            },
            addUserFormVisible: false,
            addUserForm: {
                departId: '',
                name: '',
                position: '',
                sex: '',
                phone: '',
                email: '',
                sort: 1
            },
            editUserFormVisible: false,
            editUserForm: {
                id: '',
                departId: '',
                name: '',
                position: '',
                sex: '',
                phone: '',
                email: '',
                sort: 1
            },
            userRules: {
                departId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
                name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
                sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
                position: [{ required: true, message: '请输入岗位', trigger: 'blur' }],
                sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
                phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
            }
        }
    },
    watch: {
        search(val) {
            this.$refs.tree.filter(val)
        }
    },
    computed: {
        type() {
            return localStorage.getItem('type')
        }
    },
    mounted() {
        this.queryAllData()
    },
    methods: {
        async queryAllData() {
            let res = await this.$axios.get('depart/queryAllData')
            if (res.data.code == 200) {
                this.treeData = res.data.data
            }
        },
        async queryByDepartId(departId) {
            let params = {
                departId: departId
            }
            let res = await this.$axios.get('user/queryByDepartId', { params })
            if (res.data.code == 200) {
                this.tableData = res.data.data
            }
        },
        filterNode(value, data) {
            if (!value) return true
            return data.name.indexOf(value) !== -1
        },
        sexFormatter(value) {
            if (value.sex == 1) {
                return '男'
            } else if (value.sex == 2) {
                return '女'
            } else {
                return '未知'
            }
        },
        statusFormatter(value) {
            if (value.status == 1) {
                return '正常'
            } else {
                return '禁用'
            }
        },
        handleNodeClick(data) {
            this.selected = data
            this.queryByDepartId(data.id)
        },
        handleContextMenu(event, data, node, element) {
            event.preventDefault()
            if (this.type == 2) {
                const contextMenu = document.getElementById('contextMenu')
                contextMenu.style.display = 'block'
                contextMenu.style.left = `${event.clientX}px`
                contextMenu.style.top = event.clientY + 10 + `px`
                this.selected = data
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        handleCommand(command) {
            if (command === 'addDepart') {
                const contextMenu = document.getElementById('contextMenu')
                contextMenu.style.display = 'none'
                this.addFormVisible = true
                if (this.$refs.addForm) {
                    this.$refs.addForm.resetFields()
                }
            } else if (command === 'editDepart') {
                const contextMenu = document.getElementById('contextMenu')
                contextMenu.style.display = 'none'
                this.editForm = Object.assign({}, this.selected)

                // this.editForm.code = this.selected.code.substring(
                //     this.selected.code.length - 3,
                //     this.selected.code.length
                // )
                this.editFormVisible = true
                if (this.$refs.editForm) {
                    this.$refs.editForm.resetFields()
                }
            } else if (command === 'deleteDepart') {
                const contextMenu = document.getElementById('contextMenu')
                contextMenu.style.display = 'none'
                this.$axios.post('depart/delete/' + this.selected.id, {}).then(res => {
                    if (res.data.code == 200) {
                        this.$message.success('删除成功')
                        this.queryAllData()
                    } else {
                        this.$message.error(res.data.message)
                    }
                })
            } else if (command === 'addUser') {
                this.addUserFormVisible = true
                if (this.$refs.addUserForm) {
                    this.$refs.addUserForm.resetFields()
                }
            } else if (command === 'editUser') {
                if (this.multipleSelection.length === 0) {
                    this.$message.error('请选中要编辑的用户')
                } else if (this.multipleSelection.length > 1) {
                    this.$message.error('只能选中一个用户')
                } else {
                    this.editUserForm = Object.assign({}, this.multipleSelection[0])
                    this.editUserFormVisible = true
                    if (this.$refs.editUserForm) {
                        this.$refs.editUserForm.resetFields()
                    }
                }
            } else if (command === 'deleteUser') {
                if (this.multipleSelection.length === 0) {
                    this.$message.error('请选中要删除的用户')
                } else {
                    let ids = []
                    for (let i = 0; i < this.multipleSelection.length; i++) {
                        ids.push(this.multipleSelection[i].id)
                    }
                    let params = {
                        ids: ids.toString()
                    }
                    this.$axios.post('user/delete', params).then(res => {
                        if (res.data.code == 200) {
                            this.$message.success('删除成功')
                            this.queryByDepartId(this.selected.id)
                        } else {
                            this.$message.error(res.data.message)
                        }
                    })
                }
            } else if (command === 'resetPassword') {
                if (this.multipleSelection.length === 0) {
                    this.$message.error('请选中要重置的用户')
                } else if (this.multipleSelection.length > 1) {
                    this.$message.error('只能选中一个用户')
                } else {
                    let params = {
                        id: this.multipleSelection[0].id
                    }
                    this.$axios.post('user/resetPassword', params).then(res => {
                        if (res.data.code == 200) {
                            this.$message.success('重置成功')
                            this.queryByDepartId(this.selected.id)
                        } else {
                            this.$message.error(res.data.message)
                        }
                    })
                }
            }
        },
        addSubmit() {
            var params = {
                name: this.addForm.name,
                code: this.selected.code + '' + this.addForm.code
            }
            this.$refs.addForm.validate(valid => {
                if (valid) {
                    this.$axios.post('depart/insert', params).then(res => {
                        if (res.data.code == 200) {
                            this.$message.success('新增成功')
                            this.addFormVisible = false
                            this.queryAllData()
                        } else {
                            this.$message.error(res.data.message)
                        }
                    })
                }
            })
        },
        editSubmit() {
            var params = {
                id: this.editForm.id,
                name: this.editForm.name,
                code: this.editForm.code
            }
            this.$refs.editForm.validate(valid => {
                if (valid) {
                    this.$axios.post('depart/edit', params).then(res => {
                        if (res.data.code == 200) {
                            this.$message.success('编辑成功')
                            this.editFormVisible = false
                            this.queryAllData()
                        } else {
                            this.$message.error(res.data.message)
                        }
                    })
                }
            })
        },
        addUserSubmit() {
            this.$refs.addUserForm.validate(valid => {
                if (valid) {
                    this.$axios.post('user/insert', this.addUserForm).then(res => {
                        if (res.data.code == 200) {
                            this.$message.success('新增成功')
                            this.addUserFormVisible = false
                            if (this.selected.code) {
                                this.queryByDepartId(this.selected.id)
                            }
                        } else {
                            this.$message.error(res.data.message)
                        }
                    })
                }
            })
        },
        editUserSubmit() {
            this.$refs.editUserForm.validate(valid => {
                if (valid) {
                    this.$axios.post('user/edit', this.editUserForm).then(res => {
                        if (res.data.code == 200) {
                            this.$message.success('新增成功')
                            this.editUserFormVisible = false
                            if (this.selected.code) {
                                this.queryByDepartId(this.selected.id)
                            }
                        } else {
                            this.$message.error(res.data.message)
                        }
                    })
                }
            })
        },
        handleMore(command) {
            if (command === 'template') {
                this.handleTemplate()
            }
        },
        handleTemplate() {
            let load = this.$loading({
                lock: true,
                text: '正在下载...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            let fileName = '用户模板.xlsx'
            let params = {
                templateName: 'userModel.xlsx'
            }
            this.$axios.post('upload/downloadTemplate', params, { responseType: 'blob' }).then(res => {
                let content = res.data
                let blob = new Blob([content])
                if ('download' in document.createElement('a')) {
                    // 非IE下载
                    let elink = document.createElement('a')
                    elink.download = fileName
                    elink.style.display = 'none'
                    elink.href = URL.createObjectURL(blob)
                    document.body.appendChild(elink)
                    elink.click()
                    URL.revokeObjectURL(elink.href) // 释放URL 对象
                    document.body.removeChild(elink)
                } else {
                    // IE10+下载
                    navigator.msSaveBlob(blob, fileName)
                }
                load.close()
            })
        },
        beforeUpload(file) {
            const suffix = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
            let fileType = ['xls', 'xlsx']
            if (!fileType.includes(suffix)) {
                this.$message.error(`只能选择excel文件`)
                return false
            }
            return true
        },
        successHandle(res, file, fileList) {
            if (res.code === 200) {
                this.queryByDepartId(this.selected.id)
                this.$message.success('导入成功')
            } else {
                this.$message.error(res.message)
            }
        },
        statusChange(row, value) {
            var params = {
                id: row.id,
                status: value
            }
            this.$axios.post('user/update', params).then(res => {
                if (res.data.code == 200) {
                    if (value === 1) {
                        this.$message.success('启用成功')
                    } else {
                        this.$message.success('禁用成功')
                    }
                    this.queryByDepartId(this.selected.id)
                } else {
                    this.$message.error(res.data.message)
                }
            })
        }
    }
}
</script>
<style scoped>
.org {
    display: flex;
    background: #fff;
    border-top: 1px solid #eee;
}
.contact {
    width: 250px;
    background: #fff;
    border-right: 1px solid #eee;
}
.search {
    padding: 15px 10px;
}
.contextMenu {
    display: none;
    position: absolute;
    background-color: #fff;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    font-size: 12px;
    color: #333;
    text-align: center;
    width: 80px;
}
.contextMenu div {
    line-height: 32px;
    cursor: pointer;
}
.contextMenu div:hover {
    background-color: #ebf0ff;
}
</style>
